import { NextResponse, type NextRequest } from 'next/server'; import { encodeReviewPhoto } from '@/app/lib/image-processing'; import { reviewPhotoBucket } from '@/app/lib/review-photo-storage'; import { commerceDb } from '@/app/lib/commerce-db'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { REVIEWABLE_STATUSES, REVIEW_COMMENT_LIMIT, REVIEW_DISCOVERY_SOURCE_LIMIT, REVIEW_DISCOVERY_SOURCES, REVIEW_DISPLAY_NAME_LIMIT, REVIEW_MAX_UPLOAD_BYTES, } from '@/app/lib/reviews'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) { const { id } = await ctx.params; const user = await getCustomerUser(); if (!user) return NextResponse.json({ error: 'Sign in to review your order.' }, { status: 401 }); const admin = commerceDb(); const { data: order, error: orderError } = await admin.from('orders') .select('status').eq('id', id).eq('user_id', user.id).maybeSingle(); if (orderError) return NextResponse.json({ error: 'Could not load your order. Try again.' }, { status: 500 }); if (!order) return NextResponse.json({ error: 'Order not found.' }, { status: 404 }); if (!REVIEWABLE_STATUSES.includes(order.status)) { return NextResponse.json({ error: 'Reviews open once your portrait goes to print.' }, { status: 409 }); } const form = await req.formData().catch(() => null); if (!form) return NextResponse.json({ error: 'Could not read your submission.' }, { status: 400 }); const rating = Number(form.get('rating')); const rawComment = form.get('comment'); const rawName = form.get('display_name'); const rawDiscovery = form.get('discovery_source'); const rawOther = form.get('discovery_other'); const comment = typeof rawComment === 'string' ? rawComment.trim() : ''; const displayName = typeof rawName === 'string' ? rawName.trim() : ''; const discoveryChoice = typeof rawDiscovery === 'string' ? rawDiscovery : ''; const discoveryOther = typeof rawOther === 'string' ? rawOther.trim() : ''; if (!Number.isInteger(rating) || rating < 1 || rating > 5) { return NextResponse.json({ error: 'Choose a rating from 1 to 5 stars.' }, { status: 400 }); } if (!comment || comment.length > REVIEW_COMMENT_LIMIT || displayName.length > REVIEW_DISPLAY_NAME_LIMIT) { return NextResponse.json({ error: 'Enter a comment and keep your name and comment within the listed limits.' }, { status: 400 }); } if ((rawDiscovery !== null && typeof rawDiscovery !== 'string') || (discoveryChoice && !REVIEW_DISCOVERY_SOURCES.includes(discoveryChoice))) { return NextResponse.json({ error: 'Choose one of the options for how you heard about us.' }, { status: 400 }); } if (discoveryChoice === 'Other' && (!discoveryOther || discoveryOther.length > REVIEW_DISCOVERY_SOURCE_LIMIT)) { return NextResponse.json({ error: `Tell us where you heard about us in ${REVIEW_DISCOVERY_SOURCE_LIMIT} characters or fewer.` }, { status: 400 }); } const discoverySource = discoveryChoice === 'Other' ? discoveryOther : discoveryChoice; if (form.get('permission') !== 'on') { return NextResponse.json({ error: 'Please confirm that we may display your review and any photo.' }, { status: 400 }); } const { data: existing, error: lookupError } = await admin.from('order_reviews').select('id').eq('order_id', id).maybeSingle(); if (lookupError) return NextResponse.json({ error: 'Could not check your review. Try again.' }, { status: 500 }); if (existing) return NextResponse.json({ error: 'You’ve already reviewed this order.' }, { status: 409 }); const reviewId = crypto.randomUUID(); const photo = form.get('photo'); let photoPath: string | null = null; if (photo instanceof File && photo.size > 0) { if (photo.size > REVIEW_MAX_UPLOAD_BYTES) { return NextResponse.json({ error: 'Please upload a smaller photo, up to 3 MB.' }, { status: 413 }); } let cleaned: Buffer; try { const image = await encodeReviewPhoto(Buffer.from(await photo.arrayBuffer())); if (!image) { return NextResponse.json({ error: 'Upload a JPG, PNG, or WebP photo.' }, { status: 400 }); } cleaned = image; } catch { return NextResponse.json({ error: 'That photo could not be read. Try another JPG, PNG, or WebP.' }, { status: 400 }); } photoPath = `${reviewId}.jpg`; try { await reviewPhotoBucket().put(photoPath, cleaned, { httpMetadata: { contentType: 'image/jpeg' } }); } catch { console.error('[order review] photo upload failed'); return NextResponse.json({ error: 'Could not upload the photo. Try again.' }, { status: 502 }); } } const { error } = await admin.from('order_reviews').insert({ id: reviewId, order_id: id, rating, comment, display_name: displayName || null, photo_path: photoPath, ...(discoverySource ? { discovery_source: discoverySource } : {}), }); if (error) { if (photoPath && error.code === '23505') { try { await reviewPhotoBucket().delete(photoPath); } catch { console.error('[order review] duplicate photo cleanup failed'); } } if (error.code === '23505') return NextResponse.json({ error: 'You’ve already reviewed this order.' }, { status: 409 }); console.error('[order review] save failed', { code: error.code }); return NextResponse.json({ error: 'Could not save the review. Try again.' }, { status: 500 }); } return NextResponse.json({ ok: true }, { status: 201 }); }